const { delDir, mkdirpSync } = require("./utils");
const fs = require("fs");
const replaceFileL18n = require("./replaceFileL18n");
/**
 * 替换页面
 * @param {*} context
 * @param {*} type
 */
const replacePage = async (context, type) => {
  // 文件批量替换
  delDir(context.pageDir);
  for (const [index, file] of context.contextFiles.entries()) {
    // if (file.translateStatus === false) {
    //   console.log(`==== [continue] [task=${index + 1}] translateLang`);
    //   console.log(JSON.stringify(file));
    //   continue;
    // }
    mkdirpSync(file.pageDir);
    if (fs.existsSync(file.translatePath)) {
      const langObj = fs
        .readFileSync(file.translatePath, "utf8")
        .replace("export default ", "");
      const fullFile = fs.readFileSync(file.fullPath, "utf-8");
      const isSetup = /<script.*setup/.test(fullFile);
      const { pagePath } = await replaceFileL18n(
        file.fullPath,
        file.pagePath,
        langObj,
        context,
        isSetup
      );

      const prettier = require("prettier");
      let fileContent = fs.readFileSync(file.pagePath, "utf-8");
      // 如果是 setup 模式 需要处理引入语法
      if (
        /<script.*setup/.test(fileContent) &&
        !fileContent.includes("useI18nPage")
      ) {
        const importRegex = /import\s.*(?:'\n)/g;
        const newImportStatement = `\n
          import { useI18nPage } from '@/i18n/hooks/useI18nPage'
          const { $tl } = useI18nPage('${pagePath}')
        `;
        const newCode = fileContent.replace(importRegex, (match) => {
          // 检查是否是最后一个匹配项
          const isLastMatch = !/import\s.*/g.test(
            fileContent
              .substring(fileContent.indexOf(match) + match.length)
              .substring(0, 80)
          );

          return isLastMatch ? `${match}${newImportStatement}` : match;
        });
        fileContent = newCode;
      }

      const formattedCode = await prettier.format(fileContent, {
        parser: "vue",
        ...(context.prettier || {}),
      });
      fs.writeFileSync(file.pagePath, formattedCode, "utf-8");
      console.log(`==== [success] [task=${index + 1}]`);
    } else {
      console.log(
        `==== [error] [task=${index + 1}]  translateDir is not found`
      );
    }
  }
};
module.exports = replacePage;
